package com.bolt.admin.module.sys.controller;

import com.bolt.admin.module.sys.service.CodeGeneratorService;
import com.bolt.common.io.FileUtil;
import com.bolt.common.utils.ZipUtil;
import com.bolt.convention.data.DefaultPageInfo;
import com.bolt.convention.data.PageInfo;
import com.bolt.convention.data.ResultMessage;
import com.bolt.convention.data.Results;
import com.bolt.support.codegenerator.dto.ConfigInfo;
import com.bolt.support.codegenerator.model.Column;
import com.bolt.support.codegenerator.model.Table;
import com.bolt.support.codegenerator.util.GeneratorUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "代码生成")
@RequestMapping("/api/generator")
public class CodeGeneratorController {

    @Autowired
    private CodeGeneratorService sourceCodeBuilder;

    @ApiOperation("查询数据库数据")
    @GetMapping(value = "/tables")
    public ResultMessage getAllTables(Pageable pageable, String name) {
        try {
            return Results.success(sourceCodeBuilder.findTable(pageable, name));
        } catch (Exception ex) {
            return Results.error("500", "表信息读取失败");
        }
    }

    @ApiOperation("查询表结构详细")
    @GetMapping(value = "/getTable/{tableName}")
    public ResultMessage getAllTables(@PathVariable String tableName) {
        Table table = sourceCodeBuilder.getTable(tableName);
        List <Column> columns = table.getColumns();
        PageInfo<List <Column>> data = new DefaultPageInfo(0, 10, columns, columns.size());
        return Results.success(data);
    }

    @PostMapping(value = "{tableName}/{type}")
    public ResponseEntity<Object> generator(@PathVariable String tableName, @PathVariable Integer type, @RequestBody ConfigInfo configInfo
            , HttpServletRequest request, HttpServletResponse response) {
        Table table = sourceCodeBuilder.getTable(tableName);

        if (type == 0) {
            generator(table, configInfo);
        } else if (type == 1) {
            List <Map <String, Object>> javaCode = GeneratorUtil.generatorCode(table, configInfo);
            return new ResponseEntity<>(javaCode, HttpStatus.OK);
        } else if (type == 2) {
            download(table, configInfo, request, response);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    private void generator(Table table, ConfigInfo configInfo) {
        String path = configInfo.getPath() + File.separator;
        List <Map <String, Object>> javaCode = GeneratorUtil.generatorCode(table, configInfo);
        writeFile(table, configInfo, path, javaCode);
    }


    private void download(Table table, ConfigInfo configInfo, HttpServletRequest request, HttpServletResponse response) {
        String tempPath = FileUtil.SYS_TEM_DIR + "bolt-gen-temp" + File.separator + configInfo.getTableName() + File.separator;
        List <Map <String, Object>> javaCode = GeneratorUtil.generatorCode(table, configInfo);
        writeFile(table, configInfo, tempPath, javaCode);
        File file = new File(tempPath);
        String zipPath = file.getPath() + ".zip";
        ZipUtil.zip(file.getPath(), zipPath);
        FileUtil.downloadFile(request, response, new File(zipPath), true);
    }

    private void writeFile(Table table, ConfigInfo configInfo, String path, List <Map <String, Object>> javaCode) {
        javaCode.forEach(i -> {
            String templateName = (String) i.get("name");
            String content = (String) i.get("content");
            String filePath = GeneratorUtil.getFilePath(templateName, configInfo.getPack(), table.getClassName(), path);
            FileUtil.writeUtf8String(content, filePath);
        });
    }

}

 